/**
 * Created by madi on 2018/8/13.
 */
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { Menu, Icon,Tabs ,Table, Tree,Modal ,Input,Button,message ,Row,Col,Select,Popconfirm,TreeSelect,Tooltip,DatePicker} from 'antd';
import styles from './index.less';
import { arrayToTree } from 'utils';
import moment from 'moment';
const TabPane = Tabs.TabPane;
const { TreeNode } = Tree;
const { MonthPicker, RangePicker } = DatePicker;
const { Option, OptGroup } = Select;
const Search = Input.Search;
let arrKeySub = {};
let arrKeySub_5 = {};
let arrNameSub = {};
const Pages = ({ organ, dispatch, loading }) => {

    const menuOne = organ.getOrganData ? organ.getOrganData:[];//应急

    const menuTreeOne = arrayToTree(menuOne.filter(_ => _.mpid !== '-1'), 'id', 'f_id');

    const levelMap = {};
    const getMenus = (menuTreeN, siderFoldN) => {
        const newMenu = menuTreeN.map((item) => {
            if (item.children) {
                if (item.mpid) {
                    levelMap[item.id] = item.mpid;
                }
                return (
                    <Menu.SubMenu
                        style={{width:270}}
                        key={item.id}
                        title={<span>
                            <Icon type='folder-open'/>
                            <Tooltip placement="topLeft" title={item.s_name}>
                                <span onClick={(e)=>{
                                    e.stopPropagation();
                                    dispatch({type:"organ/getTXLWB",payload:{id:item.id,type:'3'}});
                                    dispatch({type:"organ/inputOut",payload:{openKeys:{key:""},openKeysSubName:item.s_name,fistValue:item.id}});
                                }}>{item.s_name.length>8?`${item.s_name.substring(0,8)}...`:item.s_name}</span>
                            </Tooltip>

                            {
                                organ.keys == item.id &&
                                <span style={{float:'right'}}>
                                    <Icon onClick={(e)=>{
                                        e.stopPropagation();
                                        dispatch({type:"organ/inputOut",payload:{visible:true,openKeysSub:item.id}});
                                    }}type="plus" />
                                </span>
                            }
                        </span>}
                    >
                        {getMenus(item.children)}
                    </Menu.SubMenu>
                );
            }
            return <Menu.Item style={{width:270}} onClick={()=>{
                dispatch({type:"organ/inputOut",payload:{openKeysSubName:item.s_name,fistValue:item.id,noneBtn:false}});
            }} key={item.id}>
                <Icon type='folder' />
                <Tooltip placement="topLeft" title={item.s_name}>
                    {item.s_name.length>8?`${item.s_name.substring(0,8)}...`:item.s_name}
                </Tooltip>
                {
                    organ.openKeys.key == item.id &&
                    <span style={{float:'right'}}>
                        <Icon onClick={(e)=>{
                            e.stopPropagation();
                            dispatch({type:"organ/inputOut",payload:{visible:true,openKeysSub:item.id}});
                        }}type="plus" />
                    </span>
                }
            </Menu.Item>;
        });
        return newMenu;
    };
    //角色
    const columnsRole = [
        {
            title: '姓名',
            dataIndex: 'name',
        },
        {
            title: '职务',
            dataIndex: 'remark',
        },
        {
            title: '手机号',
            dataIndex: 'phone',
        },
        {
            title: '办公电话',
            dataIndex: 'callNum',
        },
        {
            title: '虚拟网号码',
            dataIndex: 'shortNum',
        },
    ];
    //组织
    const columns = [
        ...columnsRole.slice(0,5),
        {
            title: '操作',
            dataIndex: 'option',
            render: (text,record) =><div>
                <a onClick={()=>{
                    dispatch({type:"organ/inputOut",payload:{record:record,visibleTow:true}});
                }}>修改</a>
            </div>,
        },
    ];
    const rowSelection = {
        selectedRowKeys:organ.selectedRowKeys,
        onChange: (selectedRowKeys) => {
            dispatch({type:"organ/inputOut",payload:{selectedRowKeys:selectedRowKeys}});
        },
    };
    return (
        <div className={styles.container}>
            <PagesPOST dispatch={dispatch} {...organ} menuTreeOne={menuTreeOne} loading={loading.global}/>
            <div className={styles.nav}>
                <Search
                    placeholder="搜索"
                    onSearch={value => console.log(value)}
                    style={{ width: 260,marginRight:10}}
                />
                <div className={styles.TabsNew}>
                    <div style={{
                        fontSize:18,width:220,textAlign:'center',paddingBottom:10,cursor:'pointer',
                    }}>外部人员通讯录</div>
                </div>
                <div style={{height:'58vh',overflow:'auto',overflowX:"hidden"}}>
                    {
                        <Menu
                            selectedKeys={[organ.openKeys.key]}
                            mode="inline" onOpenChange={keys =>{
                                dispatch({type:"organ/inputOut",payload:{keys:keys[keys.length-1],openKeys:{}}});
                            }} onSelect={openKeys=>{
                                if(openKeys.key == organ.keys || openKeys.key == '333333'){
                                    dispatch({type:"organ/inputOut",payload:{visible:true,openKeys:openKeys}});
                                }else{
                                    dispatch({type:"organ/inputOut",payload:{openKeys:openKeys,visibleList:true}});
                                    dispatch({type:"organ/getTXLWB",payload:{id:openKeys.key,type:'3'}});
                                }
                            }}>
                            {getMenus(menuTreeOne)}
                            <Menu.Item key='333333'>
                                <Icon style={{color:'#0099FF'}} type="plus" />
                                <span style={{color:'#0099FF'}} onClick={()=>
                                    dispatch({type:"organ/inputOut",payload:{
                                        visible:true,
                                        openKeysSub:'333333',
                                    }})}>添加组织</span>
                            </Menu.Item>
                        </Menu>
                    }
                </div>
            </div>
            <div className={styles.content}>
                <h2>华电湖北发电有限公司黄石热电厂</h2>
                <b><Icon style={{marginRight:10}} type={organ.typeofZZ == 1?"folder":"team"} />{organ.openKeysSubName}</b>
                <div>
                    <Input value={organ.searchValue} onChange={e=>dispatch({type:'organ/save',payload:{searchValue:e.target.value}})}
                        style={{width:300}} placeholder='请输入姓名'/>
                    <Button type="primary" onClick={()=>
                        dispatch({type:"organ/getTXLWB",payload:{
                            id:organ.openKeys.key || organ.fistValue,
                            // type:'3',
                            // searchValue:organ.searchValue || '',
                        }})
                    }style={{margin:5}}>查询</Button>
                    <Button onClick={()=>
                        dispatch({type:"organ/inputOut",payload:{searchValue:''}})
                    }style={{margin:5}}>重置</Button>
                </div>
                <div>
                    <Button type="primary" onClick={()=>{
                        dispatch({type:"organ/inputOut",payload:{visibleTow:true,deleteValue:true}});
                        dispatch({type:"organ/getAllRole"});
                    }}style={{margin:5}}>添加成员</Button>
                    <Popconfirm title="确定移除?" onCancel={()=>{}}
                        onConfirm={()=>{
                            if(organ.selectedRowKeys && organ.selectedRowKeys.length !== 0 ){
                                dispatch({type:"organ/deleteMaillist",payload:{userId:organ.selectedRowKeys}});
                            }else{
                                message.error('未选择成员!!!');
                            }
                        }} okText="是" cancelText="否">
                        <Button style={{margin:5}}>批量删除</Button>
                    </Popconfirm>
                </div>
                <Table
                    columns={columns}
                    rowSelection={rowSelection}
                    size="small"
                    loading={loading.global}
                    pagination={{
                        pageSize: 10, //显示几条一页
                        showSizeChanger: true,
                    }}
                    rowKey={id=>id.id}
                    dataSource={organ.getTXLData || null} />
            </div>
        </div>);
};


class PagesPOST extends React.Component {

    constructor (props) {
        super(props);
        this.state = {
            name: "",
            nameADD:'',
            phoneADD:'',
            bumen:[],
            zhize:[],
            xinbie:'',
            ny:'',
            zc:'',
            phoneONEADD:'',
            phoneTOWADD:'',
            lajiValue:{},
            roleValue:'',
        };
    }
    componentWillMount () {
        this.props.dispatch({type:"organ/getOrgan",payload:{type:3}});
    }
    render (){
        let {
            visible ,
            visibleTow,
            dispatch,
            openKeysSub,
            searchValue,
            fistValue,
            loading,
            record,
        } = this.props;
        return (
            <div>
                <Modal
                    title="组织结构操作"
                    visible={visible}
                    confirmLoading={loading}
                    onOk={()=>{
                        if(this.state.name){
                            dispatch({type:"organ/postOrgan",payload:{
                                type:'3',
                                s_name:this.state.name,
                                f_id:openKeysSub,
                                duty:'职责',
                            }});
                        }else{
                            message.error('请输入名称！');
                        }
                    }}
                    onCancel={()=>{
                        dispatch({type:"organ/inputOut",payload:{visible:false}});
                    }}>
                    名称 :
                    <Input value={this.state.name}
                        placeholder="名称"
                        style={{margin:10,width:256}}
                        onChange={e=>this.setState({name:e.target.value})}/>
                </Modal>
                <Modal
                    title={record.id?"修改成员":"添加成员"}
                    visible={visibleTow}
                    confirmLoading={loading}
                    onOk={()=>{
                        let {nameADD,phoneADD,bumen,zhize,xinbie,ny,zc,phoneONEADD,phoneTOWADD} = this.state;
                        // console.log(1,nameADD, 2, phoneADD ,3, bumen,5, xinbie ,6, zc ,7,phoneONEADD ,8, phoneTOWADD)
                        if(nameADD && phoneADD && bumen && xinbie && zc && phoneONEADD && phoneTOWADD){
                            let body ={
                                name: nameADD,
                                phone:phoneADD,
                                dutys:[],
                                organizations:[],
                                sex:xinbie,
                                birthday:ny,
                                shortNum:phoneONEADD,
                                callNum:phoneTOWADD,
                                remark:zc,
                                type:'3',
                                searchValue:searchValue || '',
                                f_id:fistValue,
                            };
                            if(record.id){
                                body.id = record.id;
                            }
                            dispatch({type:record.id?"organ/putMaillist_tow":"organ/postMaillist_tow",payload:body});
                        }else{
                            message.error('请填写完整！');
                        }
                    }}
                    onCancel={()=>{
                        dispatch({type:"organ/inputOut",payload:{visibleTow:false,record:{}}});
                    }}>
                    <Row>
                        <Col span={6}><span><span style={{color:'red'}}>*</span>姓名:</span></Col>
                        <Col span={14}>
                            <Input style={{width: 300, marginBottom: 10, marginTop: -4}}
                                onChange={e => this.setState({nameADD: e.target.value})}
                                value={this.state.nameADD}
                                placeholder="名称"/>
                        </Col>
                        <Col span={6}><span><span style={{color:'red'}}>*</span>职务:</span></Col>
                        <Col span={14}>
                            <Input style={{width: 300, marginBottom: 10, marginTop: -4}}
                                onChange={e => this.setState({zc: e.target.value})}
                                value={this.state.zc}
                                placeholder="请输入应急委职务"/>
                        </Col>
                        <Col span={6}><span><span style={{color:'red'}}>*</span>手机号:</span></Col>
                        <Col span={14}>
                            <Input style={{width: 300, marginBottom: 10, marginTop: -4}}
                                onChange={e => this.setState({phoneADD: e.target.value})}
                                value={this.state.phoneADD}
                                placeholder="手机号"/>
                        </Col>
                        <Col span={6}><span><span style={{color:'red'}}>*</span>办公号:</span></Col>
                        <Col span={14}>
                            <Input style={{width: 300, marginBottom: 10, marginTop: -4}}
                                onChange={e => this.setState({phoneTOWADD: e.target.value})}
                                value={this.state.phoneTOWADD}
                                placeholder="办公电话"/>
                        </Col>
                        <Col span={6}><span><span style={{color:'red'}}>*</span>虚拟网:</span></Col>
                        <Col span={14}>
                            <Input style={{width: 300, marginBottom: 10, marginTop: -4}}
                                onChange={e => this.setState({phoneONEADD: e.target.value})}
                                value={this.state.phoneONEADD}
                                placeholder="虚拟网号码"/>
                        </Col>
                        <Col span={6}><span><span style={{color:'red'}}>*</span>性别:</span></Col>
                        <Col span={14}>
                            <Select value={this.state.xinbie?this.state.xinbie:'请选择'} style={{ width: 300, marginBottom: 10, marginTop: -4 }} onChange={value=>{
                                this.setState({
                                    xinbie:value,
                                });
                            }}>
                                <Option value='1'>男</Option>
                                <Option value='2'>女</Option>
                            </Select>
                        </Col>
                        <Col span={6}><span>出生年月:</span></Col>
                        <Col span={14}>
                            <DatePicker style={{width: 300, marginBottom: 10, marginTop: -4}}
                                value={this.state.ny?moment(this.state.ny, 'YYYY/MM/DD'):undefined}
                                placeholder="请选择(非必填)"
                                onChange={(date, dateString)=>{
                                    this.setState({ny: dateString});
                                }} />
                        </Col>
                    </Row>
                </Modal>
            </div>
        );
    }

    componentWillReceiveProps (nextProps) {
        if(!nextProps.visible){
            this.setState({
                name:'',
            });
        }
        //获取第一手数据
        if(!nextProps.fistValue && nextProps.getOrganData){
            console.log(nextProps.getOrganData[0].id);
            this.props.dispatch({type:'organ/save',payload: {
                fistValue: nextProps.getOrganData[0].id,
                openKeysSubName:nextProps.getOrganData[0].s_name,
                openKeys:nextProps.getOrganData[0].id,
            }});
            this.props.dispatch({type:"organ/getTXLWB",payload:{
                id:nextProps.getOrganData[0].id,
                type:'3',
            }});
        }
        //更新数据
        if (nextProps.record.id !== this.props.record.id) {
            let {name,phone,shortNum,birthday,sex,organizations,dutys,callNum,remark,organizationstr} = nextProps.record;
            let bumen = [],zhize = [];
            organizations && organizations.map(item=>bumen.push(item.id));
            dutys && dutys.map(item=>zhize.push(item.id));
            this.setState({
                nameADD: name,
                phoneADD:phone,
                bumen:bumen,
                zhize:organizationstr,//zhize,
                xinbie:sex,
                ny:birthday,
                phoneONEADD:shortNum,
                phoneTOWADD:callNum,
                zc:remark,
            });
        }
        //清空数据
        if(nextProps.deleteValue){
            this.setState({
                nameADD:'',
                phoneADD:'',
                bumen:[],
                zhize:[],
                xinbie:'',
                ny:'',
                zc:'',
                phoneONEADD:'',
                phoneTOWADD:'',
                roleValue:'',
                TreeSelectValue:'',
            });
            this.props.dispatch({type:"organ/save",payload:{deleteValue:false}});
        }
    }
}

Pages.propTypes = {
    organ: PropTypes.object,
    loading: PropTypes.object,
    dispatch: PropTypes.func,
};

export default connect(({ organ, loading }) => ({ organ, loading }))(Pages);
